package com.yisin.pbox.www.common.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.yisin.pbox.frame.log.ILogger;
import com.yisin.pbox.frame.log.LogFactory;
import com.yisin.pbox.frame.util.FileUtils;
import com.yisin.pbox.frame.util.StringUtil;
import com.yisin.pbox.www.common.frame.BaseAction;

/**
 * @简述：<一句话介绍>
 * @详述：<详细介绍>
 * @author admin
 * @since 1.0
 * @see
 */
@SuppressWarnings("serial")
public class DownloadFileAction extends BaseAction {
	ILogger logger = LogFactory.getDefaultLogger(DownloadFileAction.class);
	private String download;
	private String fileName;

	public InputStream getTargetFile() {
		return ServletActionContext.getServletContext().getResourceAsStream(
				download);
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFileName() {
		return this.fileName;
	}

	public String getDownload() {
		return download;
	}

	public void setDownload(String download) {
		this.download = download;
	}

	public String getFileSavePath(HttpServletRequest request) {
		String spath = request.getRealPath("");
		int index = spath.lastIndexOf("\\");
		return spath.substring(0, index + 1);
	}

	public void initParam(HttpServletRequest request) {
		setDownload(StringUtil.stringUncode(request.getParameter("download")));
		setFileName(StringUtil.toGbk(StringUtil.stringUncode(request
				.getParameter("fileName"))));
	}

	public String execute() {
		if (getUsers() == null) {
			return "error";
		}
		initParam(request);
		// 创建file对象
		File file = new File(getFileSavePath(request) + getDownload());
		// 设置response的编码方式
		response.setContentType("application/x-msdownload;charset=GB2312");
		// 写明要下载的文件的大小
		response.setContentLength((int) file.length());
		// 解决中文乱码
		response.setHeader("Content-Disposition", "attachment;filename="
				+ getFileName());
		FileInputStream fis = null;
		BufferedInputStream buff = null;
		try {
			// 读出文件到i/o流
			fis = new FileInputStream(file);
			buff = new BufferedInputStream(fis);
			byte[] b = new byte[1024];// 相当于我们的缓存
			long k = 0;// 该值用于计算当前实际下载了多少字节
			// 从response对象中得到输出流,准备下载
			response.setCharacterEncoding("GB2312");
			OutputStream myout = response.getOutputStream();
			// 开始循环下载
			while (k < file.length()) {
				int j = buff.read(b, 0, 1024);
				k += j;
				// 将b中的数据写到客户端的内存
				myout.write(b, 0, j);
			}
			// 将写入到客户端的内存的数据,刷新到磁盘
			myout.flush();
			myout.close();
			logger.info("用户【" + user.getName() + "(" + user.getAccount()
					+ ")】下载文件【" + getFileName() + "】成功！");
		} catch (IOException e) {
			logger.error(e.getMessage());
		} finally {
			try {
				fis.close();
				buff.close();
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		return null;
	}
	
	private String dirName = "attachment/";
	private String fileSavePath = "";
	
	public void image(){
		//获取请求来源  
		String linkFrom = request.getHeader("referer");
		if(linkFrom != null && !linkFrom.contains(request.getServerName())){  
			return;
		}
		
		int uid = StringUtil.stringToInt(request.getParameter("d"), -1);
		String fname = StringUtil.excNullToString(request.getParameter("n"), "");
		dirName = request.getSession().getServletContext().getContextPath() + "/" + dirName + uid;
		setFileSavePath(request);
		String filePath = fileSavePath + "/" + fname;
		File file = new File(filePath);
		if(file.exists()){
			FileInputStream fis = null;
			try {
				out = response.getOutputStream();
				fis = new FileInputStream(file);
				byte[] byt = new byte[1024];
				int i = fis.read(byt);
				while(i != -1){
					out.write(byt);
					i = fis.read(byt);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if(fis != null){
					try {
						fis.close();
						out.flush();
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public void remove(){
		int uid = StringUtil.stringToInt(request.getParameter("d"), -1);
		String fname = StringUtil.excNullToString(request.getParameter("n"), "");
		dirName = request.getSession().getServletContext().getContextPath() + "/" + dirName + uid;
		setFileSavePath(request);
		String filePath = fileSavePath + "/" + fname;
		try {
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			}
			outJson("removeFile", "success");
		} catch (Exception e) {
		}
	}
	
	public void setFileSavePath(HttpServletRequest request) {
		if (null != genre) {
			String spath = request.getServletContext().getRealPath("/");
			int index = spath.lastIndexOf("\\");
			fileSavePath = (index != -1 ? spath.substring(0, index) : spath)+ "/" + dirName + "/";
			fileSavePath = fileSavePath.replaceAll("\\\\", "/");
			fileSavePath = fileSavePath.replaceAll("///", "/");
			fileSavePath = fileSavePath.replaceAll("//", "/");
			FileUtils.createDir(fileSavePath);
		}
	}

}
